package application;

import java.util.ArrayList;
import java.io.*;

public class SearchManager {

	//Instance Variables
	database.DatabaseWrapper db;
	DocumentManager doc = new DocumentManager();
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	String[] searches = {"Within Text", "Between Text"};
	
	public SearchManager()
	{
		db = new database.DatabaseWrapper();
		setupSearch();
	}
	
	public void setupSearch()
	{
		ArrayList<String> details = new ArrayList<String>();
		ArrayList<Essay> essays = new ArrayList<Essay>();
		Essay essay;
		int typeOfSearch = Integer.parseInt(getInfo("What kind of search would you like? 1. Within Text.    2. Between Text."));
		int severity = 0;
		if((typeOfSearch > 0) && (typeOfSearch < 4) ){
			if(typeOfSearch == 2 ){
				severity = Integer.parseInt(getInfo("How pedantic should I be with the searches(1 to 5): "));
				if(!((severity >0) && (severity < 6)))
					System.err.println("Invalid Severity Value");
			}
		} else
			System.err.println("Invalid Search Type");
		
		//See how many essays we want to take in
		if(typeOfSearch == 2){
			int more = 1;
			while(more == 1){
				//Get the essay details
				details = doc.getEssay(doc.getSubjects());
				essay = new Essay(details.get(0),details.get(1));
						
				essay.setContentsFromDb(arrayToString(details));
				essays.add(essay);
				
				//Do we want another document?
				if(getInfo("Add another document? (y/n)").indexOf('y') >= 0)
					more = 1;
				else
					more = 0;
			}
		} else {
			//Get 1 essay for within text
			details = doc.getEssay(doc.getSubjects());
			essay = new Essay(details.get(0),details.get(1));
			essay.setContentsFromDb(arrayToString(details));
			essays.add(essay);
		}
		
		//Display a summary		
		System.out.println("Display Summary");
		if(typeOfSearch == 2)
			System.out.println("Performing a Between Text type search with a severity of " + severity + " in: ");
		else
			System.out.println("Performing a Within Text on: ");
		
		
		
		//Display the essay headers
		for(int i=0;i<essays.size();i++){
			essay = (Essay)essays.get(i);
			essay.getHeader();
		}		
		setupSearch();
	}
	
	public void getDocument()
	{
		ArrayList<String> subjects = new ArrayList<String>();
		subjects = doc.getSubjects();
		doc.getEssay(subjects);
	}
	
	public String getInfo(String question)
	{
		String response = "";
		System.out.print(question);
		try {
			response = in.readLine();
		} catch(Exception e){
			System.err.println("IO Exception");
			e.printStackTrace();
		}
		return response;
	}
	
	public String arrayToString(ArrayList<String> details)
	{
		String contents = "";
		for(int i=2;i<details.size();i++)
			contents += (String)details.get(i);
		return contents;
	}
}
